package com.review.Test.ReentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class UseReentrantLock {
	
	ReentrantLock rlock = new ReentrantLock();
	
	Condition condition = rlock.newCondition();
	
	public void method1(){
		try {
			rlock.lock();
			System.out.println(Thread.currentThread().getName() + rlock.isLocked());
			System.out.println(Thread.currentThread().getName() + "    进入method1");
			Thread.sleep(5000);
			System.out.println(Thread.currentThread().getName() + "    执行method1");
			condition.await();
			System.out.println(Thread.currentThread().getName() + "    退出method1");
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			rlock.unlock();
		}
		
	}
	
	
	public void method2(){
		try {
			System.out.println(Thread.currentThread().getName() +rlock.tryLock());//尝试获得锁，嗅探锁定
			System.out.println(Thread.currentThread().getName() +rlock.isLocked());
			rlock.lock();
			System.out.println(Thread.currentThread().getName() + "    进入method2");
			Thread.sleep(5000);
			System.out.println(Thread.currentThread().getName() + "    执行method2");
			condition.signal();
			System.out.println(Thread.currentThread().getName() + "    退出method2");
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			rlock.unlock();
		}
	}

	
	public static void main(String[] args) throws InterruptedException {
		
		final UseReentrantLock useReentrantLock = new UseReentrantLock();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				useReentrantLock.method1();
			}
		}, "t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				useReentrantLock.method2();
			}
		}, "t2");
		
		t1.start();
		Thread.sleep(10);
		t2.start();
	}
}
